package authentication;

import org.apache.shiro.web.servlet.ShiroFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExtendedShiroFilter extends ShiroFilter {

    private Pattern pattern;

    @Override
    public void init() throws Exception {
        String excludePatterns = super.getFilterConfig().getInitParameter("excludePatterns");
        if(excludePatterns != null && excludePatterns != ""){
            this.pattern = Pattern.compile(excludePatterns);
        }

        super.init();
    }

    @Override
    protected void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
        String url = ((HttpServletRequest)servletRequest).getServletPath().toString();
        if (matchExcludePatterns(url)) {
            chain.doFilter(servletRequest, servletResponse);
            return;
        }
        super.doFilterInternal(servletRequest, servletResponse, chain);    //To change body of overridden methods use File | Settings | File Templates.
    }

    protected boolean matchExcludePatterns(String url){
        if(pattern == null){
            return false;
        }

        Matcher matcher = pattern.matcher(url);

        return matcher.matches();
    }
}
